<?php

declare(strict_types=1);

namespace app\middleware;

use think\facade\Db;

class UserOperLog
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //只记录POST
        if ($request->isGet()) {
            return $next($request);
        }

        $request_route_rule = $request->rule()->getRule();

        $perm = str_replace('/', ':', $request_route_rule);
        $menu_name = Db::table('member_menu')->where('perms', $perm)->value('menu_name');


        $params = $request->param();
        $user_id = $request->create_by ?? 0;


        if (isset($params['password'])) {
            $params['password'] = '******';
        }
        if (isset($params['new_password'])) {
            $params['new_password'] = '******';
        }
        if (isset($params['old_password'])) {
            $params['old_password'] = '******';
        }
        Db::table('member_oper_log')->insertGetId([
            'request_method' => $request->method(),
            'oper_url' => $request_route_rule,
            'oper_ip' => $request->ip(),
            'oper_name' => $menu_name,
            'oper_param' => is_array($params) ? json_encode($params) : $params,
            'user_id' => $user_id,
            'create_time' => time()
        ]);

        return $next($request);
    }
}
